#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, os
#from PySide import QtGui, QtCore
from PyQt4 import QtGui, QtCore, Qt
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import cm, mm, inch, pica


class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.resize(800, 700)
        self.setWindowTitle('ACK')
        exit = QtGui.QAction('Kapat', self)
        exit.setShortcut('Ctrl+Q')
        exit.setStatusTip('Uygulamayi Kapat') 

        self.statusBar()
        menubar = self.menuBar()
        file = menubar.addMenu('&Dosya')
        file.addAction(exit)

        self.mainWidget = QtGui.QWidget(self)
        self.setCentralWidget(self.mainWidget)

        self.optionsWidget = QtGui.QWidget(self)

        files_list = QtGui.QListWidget()
        self.myLabel = QtGui.QLabel()
        
        create_pdf_button = QtGui.QPushButton("Pdf Olustur")
        exit_button = QtGui.QPushButton("Kapat")


        add_file_button = QtGui.QPushButton("Ekle >>>")
        remove_file_button = QtGui.QPushButton("Cikar <<<")
        
        self.listWidget = QtGui.QListWidget()
        self.listWidget.setDragDropMode(self.listWidget.InternalMove)
        self.connect(exit_button, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("close()"))
        self.connect(create_pdf_button, QtCore.SIGNAL("clicked()"), self.create_pdf)
        self.connect(add_file_button, QtCore.SIGNAL("clicked()"), self.add_file_to_list)
        self.connect(remove_file_button, QtCore.SIGNAL("clicked()"), self.remove_file_to_list)
        self.connect(self.listWidget,QtCore.SIGNAL("itemDoubleClicked(QListWidgetItem *)"),self.showItem)

             
        self.fileBrowserWidget = QtGui.QWidget(self)

        self.dirmodel = QtGui.QFileSystemModel()

        self.folder_view = QtGui.QTreeView(parent=self);
        self.folder_view.setModel(self.dirmodel)
        self.folder_view.clicked[QtCore.QModelIndex].connect(self.clicked) 
        
        self.folder_view.setHeaderHidden(False)
        self.folder_view.hideColumn(1)
        self.folder_view.hideColumn(2)
        self.folder_view.hideColumn(3)
  

        self.selectionModel = self.folder_view.selectionModel()


        group_input_file = QtGui.QGroupBox()
        grid_input_file = QtGui.QGridLayout()
        grid_input_file.addWidget(add_file_button, 0, 0)
        grid_input_file.addWidget(remove_file_button, 1, 0)
        group_input_file.setLayout(grid_input_file)   

        group_input = QtGui.QGroupBox()
        grid_input = QtGui.QGridLayout()

        splitter_filebrowser = QtGui.QSplitter()
        splitter_filebrowser.addWidget(self.folder_view)
        splitter_filebrowser.addWidget(group_input_file)
        splitter_filebrowser.addWidget(self.listWidget)
        splitter_filebrowser.setStretchFactor(0,3)
        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(splitter_filebrowser)
        self.fileBrowserWidget.setLayout(hbox)

        grid_input.addWidget(create_pdf_button, 1, 1)
        grid_input.addWidget(exit_button, 1, 2)
        group_input.setLayout(grid_input)   

        vbox_options = QtGui.QVBoxLayout(self.optionsWidget)
        vbox_options.addWidget(self.myLabel)
        vbox_options.addWidget(group_input)
        self.optionsWidget.setLayout(vbox_options)




        splitter_filelist = QtGui.QSplitter()
        splitter_filelist.setOrientation(QtCore.Qt.Vertical)
        splitter_filelist.addWidget(self.fileBrowserWidget)
        splitter_filelist.addWidget(self.optionsWidget)
        vbox_main = QtGui.QVBoxLayout(self.mainWidget)
        vbox_main.addWidget(splitter_filelist)       
        vbox_main.setContentsMargins(0,0,0,0)


    def remove_file_to_list(self):
        #print "asd"
        removed_item = self.listWidget.currentItem()
        removed_item_name = removed_item.text()
        removed_item_row = self.listWidget.row(removed_item)
        self.listWidget.takeItem(removed_item_row)
        if removed_item_name in image_list:
            image_list.pop(removed_item_name)
        #print removed_item_name      
 

    def showItem(self):
        #print "cit tiklama"
        item = self.listWidget.currentItem()
        item_name = item.text()
        if str(item_name).endswith(".jpg"):
            myImage = QtGui.QImage(50,50, QtGui.QImage.Format_ARGB32)
            myImage.load(image_list[str(item_name)]);        
            self.myLabel.setPixmap(QtGui.QPixmap.fromImage(myImage))
    
    def add_file_to_list(self):
        model = self.folder_view.currentIndex()
        #print self.dirmodel.filePath(model)
        file_path = self.dirmodel.filePath(model)
        file_name = self.dirmodel.fileName(model)
        if os.path.isdir(file_path):
            for i in os.listdir(file_path):
                if str(i).endswith(".jpg"):
                    item = QtGui.QListWidgetItem(i)
                    self.listWidget.addItem(item)
                    image_list[str(i)]=file_path + "/" + i  
                    print image_list
        else:
            image_list[file_name]=file_path
            namefile = self.dirmodel.fileName(model)
    
    #        self.myLabel.setGeometry(50, 50, 30, 30)
    #
    #        myImage = QtGui.QImage(50,50, QtGui.QImage.Format_ARGB32)
    #        myImage.load(self.dirmodel.filePath(model));        
    #        self.myLabel.setPixmap(QtGui.QPixmap.fromImage(myImage))
    #       # self.fileBrowserWidget.setLayout(myLabel)
    
            item = QtGui.QListWidgetItem(file_name)
            self.listWidget.addItem(item)
            
           # for i in range(0,self.listWidget.count()):
           #     item = self.listWidget.item(i)
           #     self.connect(self.listWidget, QtCore.SIGNAL("itemDoubleClicked(item)"), self.showItem)

    def create_pdf(self):
        images = []
        for i in range(0,self.listWidget.count()):
            item = self.listWidget.item(i)  
            images.append(item.text())
        #print images
       # fileName = QtGui.QFileDialog.getSaveFileName(self,
       #  "Save Address Book", "",
       #  "Address Book (*.abk);;All Files (*)")
        fileName = QtGui.QFileDialog.getSaveFileName(self,
         "Dosyayi Kaydet", "","Pdf Files (*.pdf);;All Files (*)")
        #print fileName
       # text, ok = QtGui.QInputDialog.getText(self, 'Dosyanın Ismini Giriniz','Dosyanin ismini giriniz:')

       # if ok:
       #     output = "/home/ahmetcan/calisma/python/resim/" + text
        c = canvas.Canvas(fileName + ".pdf" , pagesize=letter)
        for im in images:
            c.drawImage(str(image_list[str(im)]), inch, inch * 1)
            c.showPage()
            c.save()
        QtGui.QMessageBox.question(self, 'Tamamlandi', 
        '''
        Isleminiz tamamlandi.
        ''',
           QtGui.QMessageBox.Ok) 

    def set_path(self):
        self.dirmodel.setRootPath("")     

    def clicked(self, index):
        model = self.folder_view.currentIndex()
        #print self.dirmodel.filePath(model)
#        image_list.append(self.dirmodel.filePath(model))
#        namefile = self.dirmodel.fileName(model)
#
        self.myLabel.setGeometry(50, 50, 30, 30)
#
        myImage = QtGui.QImage(50,50, QtGui.QImage.Format_ARGB32)
        myImage.load(self.dirmodel.filePath(model));        
        self.myLabel.setPixmap(QtGui.QPixmap.fromImage(myImage))
#       # self.fileBrowserWidget.setLayout(myLabel)
#
#        item = QtGui.QListWidgetItem(namefile)
#        self.listWidget.addItem(item)
#        print namefile
#        print QtCore.QDir.currentPath()
#        index = self.selectionModel.currentIndex()
#        dir_path = self.dirmodel.filePath(index)



image_list = {}
app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
main.set_path()

sys.exit(app.exec_())

